<?php
  class SimpleXMLUtil{
      private $xmlPath;
      private $xml;
      
      public function __construct($xmlPath){
          $this->xmlPath = $xmlPath;
          if(!file_exists($xmlPath)){
              file_put_contents($xmlPath,"<xml>\n</xml>");
          }
      }
      
      /**
      * 打开xml文件
      * 
      */
      private function open(){
          $this->xml = simplexml_load_file($this->xmlPath); 
      } 
      
      /**
      * 从XML文件中获取节点值
      * 
      * @param mixed $name
      */
      public function getElementValue($name){
          if(!isset($this->xml)){
              $this->open();
          }
          if(isset($this->xml->$name)){
              return $this->xml->$name;
          }
          return null;
      }
      
      /**
      * 设置节点值,若无则自动增加
      * 
      * @param mixed $name
      */
      public function setElementValue($name,$value){ 
          if(!isset($this->xml)){
              $this->open();
          }
          if(is_writable($this->xmlPath)){
              if(!isset($this->xml->$name)){
                  $this->xml->addChild($name,$value);
              }
              else{
                  $this->xml->$name = $value;
              } 
          }  
          else{
              $message = $this->xmlPath."文件不能写!";
              global $log;
              $log->logError("[ERROR]$message");
              return false;
          }
      }
      
      public function save(){  
          $newXML = $this->xml->asXML();
          $fp = fopen($this->xmlPath, "w");
          fwrite($fp, $newXML);
          fclose($fp); 
          return true; 
      }
  }
?>
